package de.fhb.itunes.repository.DataAccess;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

import de.fhb.itunes.repository.data.Episode_VO;
import de.fhb.itunes.repository.data.Playlist_VO;
import de.fhb.itunes.repository.data.User_VO;
import de.fhb.itunes.repository.jdbc.DataAccessException;
import de.fhb.itunes.repository.jdbc.JdbcDAOBase;

public class DAO_User extends JdbcDAOBase implements IDAO_User {
	
	public DAO_User(){
		super();
	}
	@Override
	public User_VO getByName(String name) {
		User_VO vo;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		String sqlStr = "SELECT * FROM [itunes].[dbo].[UserSatz] WHERE Name = ?";
		try {
			con = getConnection();
			ps = con.prepareStatement(sqlStr);
			ps.setString(1, name);
			rs = ps.executeQuery();

			vo = (User_VO)transformSetToVO(rs);
		} catch (SQLException sqle) {
			throw new DataAccessException("Error executing " + sqlStr, sqle);
		} finally {
			try {
				// close the resources
				if (ps != null)
					ps.close();
				if (con != null)
					con.close();
			} catch (SQLException sqlee) {
				throw new DataAccessException("Can't close connection", sqlee);
			}
		}
		return vo;
	}

	@Override
	public List<User_VO> getAll() {
		List<User_VO> vos;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		int key = -1;

		String sqlStr = "SELECT * FROM [itunes].[dbo].[UserSatz]";

		try {
			con = getConnection();
			ps = con.prepareStatement(sqlStr);
			rs = ps.executeQuery();
			vos = (List<User_VO>) transformSet(rs);
		} catch (SQLException sqle) {
			throw new DataAccessException("Error executing " + sqlStr, sqle);
		} finally {
			try {
				// close the resources
				if (ps != null)
					ps.close();
				if (con != null)
					con.close();
			} catch (SQLException sqlee) {
				throw new DataAccessException("Can't close connection", sqlee);
			}
		}
		return vos;
	}

	@Override
	protected Object map2VO(ResultSet rs) throws SQLException {
		User_VO user = new User_VO();
		user.setID(rs.getInt("ID"));
		user.setPassword(rs.getString("Passwort"));
		user.setUsername(rs.getString("Name"));
		boolean isAdmin = false;
		if(rs.getByte("istAdmin") == 1){
			isAdmin = true;
		}
		user.setIsAdmin(isAdmin);
		
		IDAO_Playlist playlisten = new DAO_Playlist();
		user.setPlaylist(playlisten.getbyUserID(user.getID()));
		
		
		return user;
	}

}
